package com.qiji.video.service.impl;

import com.qiji.video.bean.vo.LeaderboardVo;
import com.qiji.video.mapper.extend.VideosExtendMapper;
import com.qiji.video.service.IVideoDetailService;
import com.qiji.video.util.Result;
import com.qiji.video.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import static com.qiji.video.util.RedisConstants.Video_Click_KEY_WEEK;

@Service
public class VideoDetailService implements IVideoDetailService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private VideosExtendMapper videosExtendMapper;

    @Override
    public Result findLeaderboard(Integer partitionId, Integer num) {
//        if (){
//        }
//        else{
//
//        }
        // 获取分类id，如果为0，则查询总榜
        // 获取查询条数，如果为0，则查询总榜
        // 查询所有的数量getWeek，如果week太少则查询month
        Set<ZSetOperations.TypedTuple<String>> rang = this.stringRedisTemplate.opsForZSet().reverseRangeWithScores(Video_Click_KEY_WEEK,0,1000);

        if (rang == null || rang.size()<3){
            rang = this.stringRedisTemplate.opsForZSet().reverseRangeWithScores(Video_Click_KEY_WEEK,0,1000);
        }
        if (rang == null || rang.isEmpty()){
            return ResultUtil.error("排行榜不存在");
        }
//        List<Integer> ids = rang.stream().map(Integer::valueOf).collect(Collectors.toList());
        List<Integer> ids = new ArrayList<>();
        List<Double> score = new ArrayList<>();
        for (ZSetOperations.TypedTuple<String> video : rang) {
            ids.add(Integer.parseInt(video.getValue()));
            score.add(video.getScore());
        }
        List<LeaderboardVo> leaderboardVoList = videosExtendMapper.selectLeaderboard(ids,partitionId,num);
        List<LeaderboardVo> leaderboardVoList1 = new ArrayList<>();
        int tag = 0;

        for (LeaderboardVo leaderboardVo : leaderboardVoList){

            leaderboardVo.setRealTimePopularity(score.get(tag++));
            leaderboardVoList1.add(leaderboardVo);
        }
        return ResultUtil.success(leaderboardVoList1);
    }

    @Override
    public Result findVideoByState(Integer partitionId, Integer stateNum, Integer videoNum) {
        if(stateNum.equals(0)){
            return ResultUtil.success(videosExtendMapper.selectVideosByState0(partitionId,stateNum,videoNum));
        }
        else{
            return ResultUtil.success(videosExtendMapper.selectVideosByState(partitionId,stateNum,videoNum));
        }
    }
}
